import { requestInterceptor, responseInterceptor } from './auth.js'
import config from '@/config/config.js'

// Debugging: Print the loaded config
console.log('Loaded config in request.js:', config);
console.log('config.baseUrl in request.js:', config.baseUrl);
console.log('config.apiPrefix in request.js:', config.apiPrefix);

// 请求封装
const request = (options) => {
	// 处理请求配置
	let finalUrl = options.url;
	if (!finalUrl.startsWith('http')) {
		// 如果是相对路径，确保包含 apiPrefix
		if (!finalUrl.startsWith(config.apiPrefix)) {
			finalUrl = `${config.apiPrefix}${finalUrl}`;
		}
		// 然后拼接 baseUrl
		finalUrl = `${config.baseUrl}${finalUrl}`;
	}
	options.url = finalUrl;
	
	// 初始化 header
	options.header = {
		'Content-Type': 'application/json',
		...options.header
	}
	
	// 如果是登录请求，不添加token
	if (options.url.includes('/login') || options.url.includes('/register')) {
		options.header.isToken = false
	}
	
	// 应用请求拦截器
	options = requestInterceptor(options)
	
	// 发起请求
	return new Promise((resolve, reject) => {
		console.log('发送请求：', {
			url: options.url,
			method: options.method,
			header: options.header,
			data: options.data
		})
		
		uni.request({
			...options,
			success: (res) => {
				console.log('请求响应：', res)
				
				// 如果是登录请求，直接返回响应
				if (options.url.includes('/login') || options.url.includes('/register')) {
					if (res.statusCode === 200) {
						resolve(res.data)
					} else {
						reject(res)
					}
					return
				}
				
				// 应用响应拦截器
				if (!responseInterceptor(res)) {
					reject(res)
					return
				}
				
				// 处理响应数据
				if (res.statusCode === 200) {
					if (res.data.code === 200) {
						resolve(res.data)
					} else {
						const errorMsg = res.data.msg || '请求失败'
						uni.showToast({
							title: errorMsg,
							icon: 'none',
							duration: 2000
						})
						reject(res.data)
					}
				} else {
					// 处理错误信息
					let errorMsg = '请求失败'
					if (res.data && res.data.msg) {
						errorMsg = res.data.msg
					} else if (res.data && typeof res.data === 'string') {
						try {
							const errorData = JSON.parse(res.data)
							errorMsg = errorData.msg || errorMsg
						} catch (e) {
							errorMsg = res.data
						}
					}
					
					uni.showToast({
						title: errorMsg,
						icon: 'none',
						duration: 2000
					})
					reject(res)
				}
			},
			fail: (err) => {
				console.error('请求失败：', err)
				uni.showToast({
					title: '网络异常请联系管理员',
					icon: 'none',
					duration: 2000
				})
				reject(err)
			}
		})
	})
}

export default request

// 导出请求方法
export const get = (url, data = {}, options = {}) => {
	return request({
		url,
		data,
		method: 'GET',
		...options
	})
}

export const post = (url, data = {}, options = {}) => {
	return request({
		url,
		data,
		method: 'POST',
		...options
	})
}

export const put = (url, data = {}, options = {}) => {
	return request({
		url,
		data,
		method: 'PUT',
		...options
	})
}

export const del = (url, data = {}, options = {}) => {
	return request({
		url,
		data,
		method: 'DELETE',
		...options
	})
} 